<template>
	<div class="app-container">
		<el-card class="selsctCard" v-loading="loadingTop">
			<div class="headBox">
				<div
					class="headValue"
					:class="item.dictValue === listValue ? 'bckColr' : ''"
					v-for="(item, index) in list"
					:key="index"
					@click="titleCahnge(item)">
					<span>{{ item.name }}</span>
					<span>(</span>
					<span>{{ item.value }}</span>
					<span>)</span>
				</div>
			</div>
		</el-card>
		<div v-loading="loading">
			<SearchForm
				@reset="resetQuery"
				@search="handleQuery"
				ref="searchForm"
				:label-width="labelWidth">
				<!-- <el-form-item label="审核状态" prop="auditStatus">
          <el-select v-model="queryParams.auditStatus" placeholder="请选择审核状态" clearable @change="handle_change_auditStatus">
            <el-option v-for="item in dicts.auditStatusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item> -->
				<el-form-item
					label="认领状态:"
					prop="clamStatus"
					v-if="queryParams.auditStatus == ''">
					<el-select
						v-model="queryParams.clamStatus"
						placeholder="请选择认领状态"
						clearable>
						<el-option
							v-for="item in dicts.claimStatusList"
							:key="item.value"
							:label="item.label"
							:value="item.value"></el-option>
					</el-select>
				</el-form-item>

				<el-form-item label="客户名称:" prop="customName">
					<el-input
						v-model="queryParams.customName"
						placeholder="请输入客户名称"
						clearable
						size="small"
						@keyup.enter.native="handleQuery" />
				</el-form-item>
				<el-form-item label="所属公司:">
					<el-select
						v-model="queryParams.companyId"
						placeholder="请选择公司"
						clearable>
						<el-option
							v-for="item in deptList.company"
							:label="item.deptName"
							:value="item.deptId"
							:key="item.deptId"></el-option>
					</el-select>
				</el-form-item>

				<!-- <el-form-item
                    label="业务类型:"
                    prop="category"
                    v-if="listValue !== ''"
                >
                    <el-select
                        v-model="queryParams.businessType"
                        placeholder="请选择业务类型"
                        clearable
                    >
                        <el-option
                            v-for="item in business_type"
                            :label="item.label"
                            :value="item.value"
                            :key="item.value"
                        >
                        </el-option>
                    </el-select>
                </el-form-item> -->
				<el-form-item label="业务单号:" prop="businessId">
					<el-input
						v-model="queryParams.businessId"
						placeholder="请输入业务单号"
						clearable
						size="small"
						@keyup.enter.native="handleQuery" />
				</el-form-item>
				<el-form-item label="业务名称:" prop="businessName">
					<el-input
						v-model="queryParams.businessName"
						placeholder="请输入业务名称"
						clearable
						size="small"
						@keyup.enter.native="handleQuery" />
				</el-form-item>
				<el-form-item label="产品类型:" prop="post">
					<el-select
						v-model="queryParams.productType"
						placeholder="请选择产品类型"
						clearable>
						<el-option
							v-for="item in dict.type.quota_rent_type"
							:label="item.label"
							:value="item.value"
							:key="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="渠道/自营:">
					<el-select
						v-model="queryParams.operateType"
						placeholder="请选择渠道/自营"
						clearable>
						<el-option
							v-for="item in dict.type.business_type"
							:label="item.label"
							:value="item.value"
							:key="item.value"></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="暂存状态:">
					<el-select
						v-model="queryParams.suspensionState"
						placeholder="请选择暂存状态"
						clearable>
						<el-option
							v-for="item in storageStatus"
							:label="item.label"
							:value="item.value"
							:key="item.value"></el-option>
					</el-select>
				</el-form-item>
			</SearchForm>

			<div class="card-wrap card-padding">
				<div class="table-title-wrap justify-end">
					<el-button
						type=""
						icon="el-icon-upload2"
						size="mini"
						@click="exportFile"
						v-hasPermi="['flowable:examine:list:export']">
						导出
					</el-button>
				</div>
				<div class="tableBox">
					<el-table
						:key="listValue"
						ref="elTable"
						fit
						:data="definitionList"
						border
						v-if="tableCloumns.length > 0">
						<el-table-column
							label="操作"
							width="150"
							align="center">
							<template slot-scope="scope">
								<el-button
									@click="handleReadImage(scope.row, '1')"
									type="text"
									size="small"
									v-hasPermi="['flowable:examine:list:look']">
									查看
								</el-button>
								<el-button
									v-if="
										scope.row.processStatus !== 2 &&
										queryParams.auditStatus == '' &&
										scope.row.isSuspended !== true &&
										scope.row.claimStatus == 1
									"
									@click="handleReadImage(scope.row, '2')"
									type="text"
									size="small"
									v-hasPermi="[
										'flowable:examine:list:audit',
									]">
									审核
								</el-button>
								<el-button
									v-if="
										scope.row.claimStatus == 0 &&
										scope.row.processStatus !== 2 &&
										queryParams.auditStatus == '' &&
										scope.row.isSuspended !== true
									"
									@click="taskClaim(scope.row)"
									type="text"
									size="small"
									v-hasPermi="[
										'flowable:examine:list:claim',
									]">
									认领
								</el-button>
							</template>
						</el-table-column>
						<TableCloumn
							v-for="item in tableCloumns"
							:cellOptions="item"></TableCloumn>
					</el-table>

					<pagination
						v-show="total > 0"
						:total="total"
						:page.sync="queryParams.pageNum"
						:limit.sync="queryParams.pageSize"
						@pagination="getList" />
				</div>
			</div>
		</div>
	</div>
</template>

<script>
	import * as apis from '@/api/flowable/examine/list/api.js';
	import SearchContent from '@/components/SearchContent/index.vue';
	import { getDicts } from '@/api/system/dict/data.js';
	import Cookies from 'js-cookie';
	import TableCloumn from '@/views/finance/manage/tableColumn/index.vue';
	import { getCCUser } from '@/api/flowable/model';
	export default {
		name: 'Approve',
		dicts: [
			'sys_process_category',
			'expense_business_type',
			'bus_flow_type',
			'work_order_type',
			'quota_rent_type',
			'template_classification',
			'other_contract_template_type',
			'contract_template_edit_type',
			'rental_purpose',
			'return_car_type',
			'external_business_type',
			'external_perfect_type',
			'business_type',
			'quota_source_business',
		],
		components: {
			SearchContent,
			TableCloumn,
		},
		data() {
			return {
				loadingTop: false,
				// 遮罩层
				loading: true,
				// 显示搜索条件
				showSearch: true,
				// 总条数
				total: 0,
				// 流程定义表格数据
				definitionList: [],
				// 弹出层标题
				title: '',
				// 是否显示弹出层
				open: false,
				// 查询参数
				queryParams: {
					pageNum: 1,
					pageSize: 10,
					id: '1',
					groupId: '1',
					auditStatus: '',
					clamStatus: null,
					businessId: null,
					orgIds: '',
					category: '',
					businessType: '',
				},
				formQueryParams: {
					pageNum: 1,
					pageSize: 10,
				},
				// 挂载表单到流程实例
				formDeployParam: {
					formId: null,
					deployId: null,
				},
				deployId: '',
				// xml
				flowData: {},
				auditStatus: '',
				listValue: '',
				list: [],
				business_type: [],
				dicts: {
					claimStatusList: [
						{
							label: '未认领',
							value: '0',
						},
						{
							label: '已认领',
							value: '1',
						},
					],
					auditStatusList: [
						{
							label: '待办',
							value: '',
						},
						{
							label: '审核通过',
							value: '7',
						},
						{
							label: '审核驳回',
							value: '3',
						},
						{
							label: '审核拒绝',
							value: '5',
						},
					],
					operateTypeList: [
						{
							label: '渠道',
							value: '渠道',
						},
						{
							label: '自营',
							value: '自营',
						},
					],
					busFlowTypeList: [],
				},
				tableCloumns: [],
				dictType: '',
				labelWidth: '200',
				CCUserList: [],
				deptList: {
					company: [], //公司
					department: [], // 组织
				},
				storageStatus: [
					{
						label: '未暂存',
						value: 1,
					},
					{
						label: '已暂存',
						value: 3,
					},
				],
			};
		},
		// watch: {
		//     business_type: {
		//         handler(val) {
		//             console.log(val, "[========]");
		//         },
		//         immediate: true,
		//     },
		// },
		async mounted() {
			try {
				this.loading = true;
				this.busFlowTypeList = await this._getDicts('bus_flow_type');
				this.initDeptList();
				this.init();
				this.getList();
				this.getCcUsers();
			} catch {
				throw new Error('Error');
			}
		},
		activated() {
			this.initDeptList();
			this.init();
			this.getList();
			this.getCcUsers();
		},
		methods: {
			initDeptList() {
				this.getDeptList(1);
				this.getDeptList(2);
			},
			getDeptList(deptType) {
				let params = {
					deptType,
				};
				apis.DeptList(params).then(res => {
					if (res.code == 200) {
						switch (deptType) {
							case 1:
								this.deptList.department = res?.data ?? [];
								break;
							case 2:
								this.deptList.company = res?.data ?? [];
								break;
						}
					}
				});
			},
			// 获取调单用户人员
			getCcUsers() {
				getCCUser().then(res => {
					this.CCUserList = [];
					res.data.map(item => {
						let obj = {
							label: item.nickName,
							value: item.userId?.toString(),
						};

						this.CCUserList.push(obj);
					});
				});
			},
			async init(flag = '1') {
				await this.getList_task(flag);
				let isShow = this.list.filter(item => {
					if (item.dictValue == this.listValue) {
						return item;
					}
				})[0]?.dictValue;
				if (isShow == undefined) {
					this.listValue = '';
				}
				await this.getList();
				this.setTabloCloumns();
			},
			getList_task(flag) {
				return new Promise((resolve, reject) => {
					this.loadingTop = true;
					this.list = [];
					let params = {
						flag,
						auditStatus: this.queryParams.auditStatus,
					};
					apis?.List_task(params)
						.then(res => {
							this.loadingTop = false;
							if (!res?.rows || res?.rows?.length == 0) {
								this.list.push({
									name: '全部',
									value: 0,
									dictValue: '',
								});
							} else {
								res?.rows?.map(item => {
									if (item.category == 'total') {
										this.list.push({
											name: '全部',
											value: item.value,
											dictValue: '',
										});
									} else {
										let ele = this.busFlowTypeList.find(
											e => {
												return (
													item.category == e.dictValue
												);
											},
										);
										if (ele) {
											this.list.push({
												name: ele.dictLabel,
												value: item.value,
												dictValue: ele.dictValue,
											});
										}
									}
								});
							}
							resolve(res.data);
						})
						.catch(() => {
							this.loadingTop = false;
							resolve([]);
						});
				});
			},
			handle_change_auditStatus(val) {
				this.queryParams = {
					pageNum: 1,
					pageSize: 10,
				};
				this.queryParams.auditStatus = val;
				if (val == '') {
					this.init('1');
				} else {
					this.init('2');
				}
			},
			exportFile() {
				if (!apis?.ExportFile) return;
				let exportFlag = '1';
				let fileName = '待办列表';
				let params = {
					...this.queryParams,
					dictType: this.listValue ? this.dictType : '',
					exportFlag,
				};
				delete params.pageNum;
				delete params.pageSize;
				this.download(
					apis?.ExportFile,
					params,
					`${fileName}_${new Date().getTime()}.xlsx`,
				);
			},
			// 按钮切换
			titleCahnge({ name, value, dictValue }) {
				this.listValue = dictValue;
				this.queryParams.businessType = '';
				this.queryParams.pageNum = 1;
				this.queryParams.pageSize = 10;
				this.$refs.searchForm.resize();
				this.queryParams.category = dictValue;
				this.setDict();
				this.setTabloCloumns();
				this.getList();
			},
			setDict() {
				switch (this.listValue) {
					case '3': // 费用报销
						this.business_type =
							this.dict.type.expense_business_type;
						this.dictType = 'expense_business_type';
						break;
					case '29': // 合同模板
						this.business_type =
							this.dict.type.template_classification;
						this.dictType = 'template_classification';
						break;
					case '30': // 其他合同模板
						this.business_type =
							this.dict.type.other_contract_template_type;
						this.dictType = 'other_contract_template_type';
						break;
					case '28': // 合同模板修改申请
						this.business_type =
							this.dict.type.contract_template_edit_type;
						this.dictType = 'contract_template_edit_type';
						break;
					case '2': // 信审流程
						this.business_type = this.dict.type.rental_purpose;
						this.dictType = 'rental_purpose';
						break;
					case '36': // 订单还车
						this.business_type = this.dict.type.return_car_type;
						this.dictType = 'return_car_type';
						break;
					case '41': // 外部转租赁业务类型
						this.business_type =
							this.dict.type.external_business_type;
						this.dictType = 'external_business_type';
						break;
					case '42': // 外部转租赁信息完善业务
						this.business_type =
							this.dict.type.external_perfect_type;
						this.dictType = 'external_perfect_type';
						break;
					case '4':
					case '5':
					case '6':
						this.business_type = this.dict.type.work_order_type;
						this.dictType = 'work_order_type';
						break;
					default:
						this.business_type = [];
						this.dictType = '';
						break;
				}
			},
			setTabloCloumns() {
				switch (this.listValue) {
					case '': // 全部
						this.setTabloCloumns_0();
						break;
					default:
						this.setTabloCloumns_1();
						break;
				}
			},
			translateDict(dict, value) {
				let word = '-';
				let result = [];
				let prop = value?.split?.(',');

				dict?.map(item => {
					if (prop?.includes(item.value ?? item.dictValue)) {
						result.push(item.label ?? item.dictLabel);
					}
				});
				word = result && result?.join('/');

				return word;
			},
			// 全部
			setTabloCloumns_0() {
				this.business_type = [];
				this.tableCloumns = [
					{
						label: '审核类型',
						prop: 'category',
						minWidth: '150px',
						type: 'dict',
						dict: this.dict.type.bus_flow_type,
					},
					{
						label: '审核节点',
						prop: 'name',
						minWidth: '150px',
					},
					{
						label: '所属公司',
						prop: 'companyName',
					},
					{
						label: '客户名称',
						prop: 'customName',
					},
					{
						label: '车牌号',
						prop: 'carNo',
					},
					{
						label: '产品类型',
						prop: 'productType',
						format: row => {
							if (this.notEmpty(row.productType)) {
								if (isNaN(row.productType * 1)) {
									return row.productType;
								} else {
									console.log(item)
									let item =
										this.dict.type?.quota_rent_type?.find(
											e => e.value == row.productType,
										);
									return item.label;
								}
							} else {
								return '-';
							}
						},
					},
					{
						label: '渠道/自营',
						// prop: "operateType",
						format: row => {
							if (this.notEmpty(row.operateType)) {
								if (isNaN(row.operateType * 1)) {
									return row.operateType;
								} else {
									let item =
										this.dict.type?.quota_source_business?.find(
											e => e.value == row.operateType,
										);
									return item.label;
								}
							} else {
								return '-';
							}
						},
					},
					{
						//   label: "所属月份",
						//   minWidth: "100px",
						//   format: (row) => {
						//     return this._formatTime(row.businessTime, "YYYY-MM");
						//   },
						label: '所属月份',
						prop: 'businessTime',
						minWidth: '100px',
					},
					// {
					//     label: "调单用户",
					//     prop: "adjustOperateName",
					// },
					// {
					//     label: "调单来源人",
					//     minWidth: "120px",
					//     prop: "adjustSourceName",
					// },
					{
						label: '认领状态',
						prop: 'claimStatusName',
					},
					{
						label: '业务单号',
						prop: 'businessId',
						minWidth: '200px',
						prototype: {
							class: 'state_orderID',
						},
					},
					{
						label: '业务名称',
						prop: 'businessName',
					},
					
					// {
					//   label: "审核状态",
					//   minWidth: "150px",
					//   prop: "auditStatus",
					// prototype: {
					//   class: "state_red",
					// },
					// format: (row) => {
					//   return row?.auditStatus ?? "审核通过";
					// },
					// },
					{
						label: '当前处理人',
						prop: 'assigneeName',
					},
					{
						label: '发起人',
						prop: 'startUserName',
					},
					{
						label: '发起时间',
						prop: 'startTime',
						minWidth: '150px',
					},
					{
						label: '上一节点提交时间',
						prop: 'createTime',
						minWidth: '150px',
					},
					{
						label: '审核等待时间',
						prop: 'duration',
						minWidth: '150px',
					},
				];
			},
			// 费用报销
			setTabloCloumns_1() {
				this.tableCloumns = [
					{
						label: '审核类型',
						prop: 'category',
						type: 'dict',
						minWidth: '150px',
						dict: this.dict.type.bus_flow_type,
					},
					{
						label: '审核节点',
						prop: 'name',
						minWidth: '150px',
					},
					{
						label: '所属公司',
						prop: 'companyName',
					},
					{
						label: '客户名称',
						prop: 'customName',
					},
					{
						label: '车牌号',
						prop: 'carNo',
					},
					{
						label: '产品类型',
						prop: 'productType',
						format: row => {
							if (this.notEmpty(row.productType)) {
								if (isNaN(row.productType * 1)) {
									return row.productType;
								} else {
									console.log(item)
									let item =
										this.dict.type?.quota_rent_type?.find(
											e => e.value == row.productType,
										);
									return item.label;
								}
							} else {
								return '-';
							}
						},
					},
					{
						label: '渠道/自营',
						prop: 'operateType',
						format: row => {
							if (this.notEmpty(row.operateType)) {
								if (isNaN(row.operateType * 1)) {
									return row.operateType;
								} else {
									let item =
										this.dict.type?.quota_source_business?.find(
											e => e.value == row.operateType,
										);
									return item.label;
								}
							} else {
								return '-';
							}
						},
					},
					{
						label: '所属月份',
						prop: 'businessTime',
						minWidth: '100px',
						//   format: (row) => {
						//     return this._formatTime(row.businessTime, "YYYY-MM");
						//   },
					},
					// {
					//     label: "业务类型",
					//     prop: "businessType",
					//     type: "select",
					//     selectList: this.business_type,
					//     state: "readonly",
					//       format: (row) => {
					//         if (this.business_type?.length > 0) {
					//           return this.translateDict(
					//             this.business_type,
					//             row.businessType
					//           );
					//         } else {
					//           return row.businessType;
					//         }
					//       },
					// },
					// {
					//     label: "调单用户",
					//     prop: "adjustOperateName",
					// },
					// {
					//     label: "调单来源人",
					//     minWidth: "120px",
					//     prop: "adjustSourceName",
					// },
					{
						label: '认领状态',
						prop: 'claimStatusName',
					},
					{
						label: '业务单号',
						prop: 'businessId',
						minWidth: '200px',
						prototype: {
							class: 'state_orderID',
						},
					},
					{
						label: '业务名称',
						prop: 'businessName',
					},
					
					// {
					//   label: "审核状态",
					//   minWidth: "150px",
					//   prop: "auditStatus",
					// prototype: {
					//   class: "state_red",
					// },
					// format: (row) => {
					//   return row?.auditStatus ?? "审核通过";
					// },
					// },
					{
						label: '当前处理人',
						prop: 'assigneeName',
					},
					{
						label: '发起人',
						prop: 'startUserName',
					},
					{
						label: '发起时间',
						prop: 'startTime',
						minWidth: '150px',
					},
					{
						label: '上一节点提交时间',
						prop: 'createTime',
						minWidth: '150px',
					},
					{
						label: '审核等待时间',
						prop: 'duration',
						minWidth: '150px',
					},
				];
			},

			/** 查询流程定义列表 */
			getList() {
				this.loading = true;
				let param = JSON.parse(JSON.stringify(this.queryParams));
				// if(param.suspensionState==0){
				//     param.suspensionState = ''
				// }
				apis?.List(param)
					.then(response => {
						if (response.code == 200) {
							this.definitionList = response.rows;
							this.total = response.total;
						}
					})
					.finally(() => (this.loading = false));
			},
			activeItem(row) {
				this.$confirm('是否确认激活此任务?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				}).then(() => {
					let params = {
						state: '1',
						id: row.id,
						taskId: row.taskId,
						remark: '',
					};
					// console.log(params);
					// return;
					apis?.UpdateState(params).then(res => {
						if (res.code == 200) {
							this.$message.success('激活成功');
							this.getList();
						}
					});
				});
			},
			/** 搜索按钮操作 */
			handleQuery() {
				this.queryParams.pageNum = 1;
				this.getList();
			},
			/** 重置按钮操作 */
			resetQuery() {
				this.queryParams = {
					pageNum: 1,
					pageSize: 10,
					id: Cookies.get('userId'),
					groupId: '1',
					category: null,
					auditStatus: '',
					clamStatus: null,
					businessId: null,
					orgIds: '',
					businessType: '',
				};
				this.queryParams.pageNum = 1;
				this.init();
			},
			taskClaim(row) {
				this.$confirm('是否确认认领此任务?', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						let params = {
							processInstanceId: row?.id ?? row?.processId,
						};
						apis?.TaskClaim(params)
							.then(res => {
								if (res.code == 200) {
									this.$message({
										type: 'success',
										message: '认领成功!',
									});
									this.getList();
								}
							})
							.finally(() => {});
					})
					.catch(() => {});
			},
			/** 流程图查看 */
			handleReadImage(info, flag) {
				let processId =
					this.queryParams.auditStatus == ''
						? info?.id
						: info?.processId;
				let query = {
					modelId: processId,
					name: info.name,
					category: info.category,
					deployId: info.deploymentId,
					processId: processId,
					taskId: info?.taskId,
					activityId: info?.activityId,
					isSuspended: info?.isSuspended,
					flag: flag,
				};
				if (flag == '1') {
					query.status = 'readonly';
				}
				this.$router.push({
					path: '/workflow/examine/details',
					query: query,
				});
			},

			/** 挂起/激活流程 */
			handleUpdateSuspensionState(row, type) {
				const params = {
					id: row.id,
					state: type,
				};
				updateState(params).then(res => {
					this.$modal.msgSuccess(res.msg);
					this.getList();
				});
			},
		},
	};
</script>
<style scoped lang="scss">
	.selsctCard {
		margin-bottom: 20px;
		border-radius: 8px;

		.headBox {
			width: 100%;
			min-height: 30px;
			// height: 30px;
			line-height: 30px;
			display: flex;
			gap: 15px;
			flex-wrap: wrap;
			// justify-content: space-between;

			.headValue {
				// width: 15%;
				padding: 0 13px;
				height: 30px;
				line-height: 30px;
				text-align: center;
				font-size: 14px;
				border: 1px solid #ccc;
				border-radius: 5px;
				cursor: pointer;
			}

			.bckColr {
				color: #fff;
				background: #1890ff;
			}
		}
	}
</style>
